import React,{ useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { AtNavBar } from 'taro-ui'
import { View, Image, Text, Swiper, SwiperItem } from '@tarojs/components'
import "taro-ui/dist/style/components/nav-bar.scss";
import './index.less'

export default function PlusCenter(props) {
let capsuleInfo = {}
if(process.env.TARO_ENV === 'weapp') capsuleInfo = Taro.getMenuButtonBoundingClientRect()
const [info, setinfo] = useState({})
const [curSwiper, setcurSwiper] = useState(0)
useEffect(()=>{
  Taro.$get('/wallet/paid/ruleList').then(res=>{
    if(res.code =='1') setinfo(res.content)
  })
},[])
const handleOpenCard =e=>{
  Taro.verifyLogin()
  Taro.showModal({
    title:'提示',
    content:'是否开通会员?',
    success:res=>{
      if(res.confirm){
        Taro.showLoading({title:'加载中...'})
        Taro.$post('/wallet/levelOrder/create',{
          "memberId": info.memberId,
          "ruleId": info.paidRuleList[curSwiper].ruleId,
          "type": 1
        },'1').then(async ret=>{
          if(ret.code == '1'){
            const data = {
              "appId":Taro.$mpAppid,
              "openId":await Taro.getOpenId(),
              "orderId": ret.content.orderId
            }
            Taro.showLoading({title:'加载中...'})
            Taro.$post('/wallet/levelOrder/pay',data,'1').then(res=>{
              if(res.code == '1'){
                handlePay(res.content,ret.content.orderId)
              }else{
                Taro.$toast(res.message)
              }
            })
          }else{
            Taro.$toast(ret.message)
          }
        })
      }
    }
  })
}
const handlePay =(content,orderId)=>{
  if(process.env.TARO_ENV == 'tt'){
    tt.pay({
      orderInfo: {
        order_id:content.data.orderId,
        order_token: content.data.orderToken
      },
      service: 5,
      _debug:1,
      success:res=>{
        if(res.code == 0){
          Taro.navigateBack().catch(e=>{
            Taro.reLaunch({
              url:'/pages/mine/cinema-index/index'
            })
          })
        }
      },
      fail:err=>{
        Taro.$toast('支付失败')
      }
    });
    return;
  }
  if(process.env.TARO_ENV == 'h5' && navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger"){
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
      "appId": Taro.$mpAppid,
      "timeStamp": content.timeStamp,   
      "nonceStr": content.nonceStr,  
      "package": content.packageStr,
      "signType": content.signType,    
      "paySign":content.paySign
    },(result) => {
      if(result.err_msg == "get_brand_wcpay_request:cancel"){
        Taro.$toast('取消支付','error')
      }else{
        Taro.navigateBack().catch(e=>{
          Taro.reLaunch({
            url:'/pages/mine/cinema-index/index'
          })
        })
      }
    });
    return;
  }
  Taro.requestPayment({
    timeStamp: content.timeStamp,
    nonceStr: content.nonceStr,
    package: content.package,
    signType: content.signType,
    paySign: content.paySign,
    success:res=>{
      Taro.navigateBack().catch(e=>{
        Taro.reLaunch({
          url:'/pages/mine/cinema-index/index'
        })
      })
    },
    fail:err=>{
      Taro.$toast('支付失败')
    }
  })
}
return (
  <View className="plus-center">
    <View style={{background:"#fbe5a9"}}>
      <View className="center-crumbs" style={{'paddingTop': capsuleInfo?.top+'px'}}>
        <AtNavBar style={{height: capsuleInfo?.height+'px'}} border={false} onClickLeftIcon={e=>{
          Taro.navigateBack().catch(e=>{
            Taro.reLaunch({
              url:'/pages/mine/cinema-index/index'
            })
          })
        }} title='会员中心' leftIconType="close" />
      </View>
      {info.paidRuleList?.length?
      <View className="center-swiper">
        <Swiper className='swiper' previousMargin='10px' nextMargin="10px" current={curSwiper} onChange={e=>{
          setcurSwiper(e.detail.current)
        }}>
          {info.paidRuleList.map(item=>{
            return <SwiperItem className='swiper-item' key={item}>
              <View className="item-box">
                <View className="item-title">{item.ruleName || '会员中心'}</View>
                <View className="item-footer">
                  <View className="footer-info">
                    {/* <View className="sub">连续包月</View> */}
                    <View className="price">￥<Text className='h2'>{item.price}</Text> 开通</View>
                    {/* <View className="p">到期￥{item.price}/{item.periodValidity}个月自动续费，可随时取消</View> */}
                    {/* <View className="p">联合会员权益仅开通年卡可享</View> */}
                  </View>
                  <View className="footer-button" onClick={e=>{handleOpenCard()}}>立即开卡</View>
                </View>
              </View>
            </SwiperItem>
          })}
        </Swiper>
        <View className="swiper-section">
          <View className="section-title">开通会员获得以下{info.paidEquityDtos?.length || 0}项特权</View>
          <View className="section-list">
            {info.paidEquityDtos?.map(res=>{
              return <View className="section-item" key={res.equityId}>
                <Image src={res.equityIconPath} className="section-icon" mode='aspectFill' />
                <Text className="section-text">{res.equityName}</Text>
              </View>
            })}
          </View>
        </View>
      </View>:<View className='var-empty'>暂无数据</View>}
    </View>
    {info.memberId?
    <View className="center-footer" onClick={e=>{ handleOpenCard() }}>
      <View className="button">￥{info.paidRuleList[curSwiper].price}元开通</View>
    </View>:null}
  </View>
)}